#include "hole.h"
#include "board.h"
#include "rock.h"

#include <QPainter>

Hole::Hole(Board* board, qreal w, qreal h, QGraphicsItem *parent)
    : board_(board)
    , w_(w)
    , h_(h)
    , hasRock_(false)
    , QGraphicsItem(parent)
{
    //setFlag(ItemIsMovable, true);
}

QRectF Hole::boundingRect() const {
    return QRectF(0, 0, w_, h_);
}

QPainterPath Hole::shape() const
 {
     QPainterPath path;
     path.addEllipse(boundingRect());
     return path;
 }


void Hole::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
//    QPen circlePen(Qt::black);
//    circlePen.setWidth(1);
//    painter->setPen(circlePen);
    painter->setBrush(Qt::black);
    painter->drawEllipse(boundingRect());
}

void Hole::setCoords(int row, int col)
{
    row_ = row;
    col_ = col;
}

int Hole::row() const
{
    return row_;
}

int Hole::col() const
{
    return col_;
}

qreal Hole::rockX() const
{
    return scenePos().x() + w_ / 2;
}

qreal Hole::rockY() const
{
    return scenePos().y() + h_ / 2;
}

bool Hole::hasRock()
{
    return hasRock_;
}

void Hole::setHasRock(bool hasRock)
{
    hasRock_ = hasRock;
}

bool Hole::availableNextHole(Hole* hole) {
    if (row_ == hole->row()
            && (col_ == hole->col() - 2 || col_ == hole->col() + 2)
            && board_->getHole(row_, col_ + (hole->col() > col_ ? 1 : -1))->hasRock()) {
        return true;
    }

    if (col_ == hole->col()
            && (row_ == hole->row() - 2 || row_ == hole->row() + 2)
            && board_->getHole(row_ + (hole->row() > row_ ? 1 : -1), col_)->hasRock()) {
        return true;
    }
    return false;
}

Rock* Hole::getRock() {
    Rock* rock = 0;

    QList<QGraphicsItem *> items = collidingItems();
    for (auto i = items.begin(); i != items.end(); ++i) {
        rock = qgraphicsitem_cast<Rock *>(*i);
        if (rock != 0) {
            break;
        }
    }

    return rock;
}

Board *Hole::getBoard()
{
    return board_;
}
